package com.piece.module.file.util.convert;

import com.piece.core.framework.util.file.FileUtil;
import com.piece.core.framework.util.file.IoUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import ws.schild.jave.MultimediaObject;
import ws.schild.jave.info.MultimediaInfo;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

@Slf4j
public class FileConvert {

    /**
     * 复制文件
     */
    public static MultipartFile copy(String fileName, byte[] bytes) throws IOException {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        FileItem item = factory.createItem("file", "text/plain", true, fileName);
        OutputStream os = item.getOutputStream();
        IoUtil.write(os, bytes, true, false);
        return new CommonsMultipartFile(item);
    }

    /**
     * 解析文件时长
     */
    public static long parseDuration(String fileName, byte[] bytes) {
        long duration = 0l;
        File tempFile = new File(FileUtil.getTempPath() + File.separator + fileName);
        try {
            FileUtil.writeByteArrayToFile(tempFile, bytes);
            MultimediaObject instance = new MultimediaObject(tempFile);
            MultimediaInfo result = instance.getInfo();
            duration = result.getDuration() / 1000;
        } catch (Exception e) {
            log.error(e.getMessage());
        } finally {
            FileUtil.deleteQuietly(tempFile);
        }
        return duration;
    }

    /**
     * 时长格式转化
     */
    public static String covertDuration(long duration) {
        String length;
        Integer hour = (int) (duration / 3600);
        Integer minute = (int) (duration % 3600) / 60;
        Integer second = (int) (duration - hour * 3600 - minute * 60);
        String hr = hour.toString();
        String mi = minute.toString();
        String se = second.toString();
        if (hr.length() < 2) {
            hr = "0" + hr;
        }
        if (mi.length() < 2) {
            mi = "0" + mi;
        }
        if (se.length() < 2) {
            se = "0" + se;
        }

        String noHour = "00";
        if (noHour.equals(hr)) {
            length = mi + ":" + se;
        } else {
            length = hr + ":" + mi + ":" + se;
        }

        return length;
    }
}
